<template>
  <ele-modal
    form
    :width="900"
    :model-value="modelValue"
    title="账单录入"
    @update:modelValue="updateModelValue"
  >
    <ele-page>
      <ele-card class="step-card">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="118px">
          <el-form-item label="车辆信息" prop="vehicle_id">
            <span
              class="blue pointer"
              v-if="form.vehicle_id == 0"
              @click="openVehicle"
              >请选择</span
            >
            <span class="blue pointer" @click="openVehicle" v-else>{{
              selectedVehicle
            }}</span>
          </el-form-item>
          <el-form-item label="所属区域">
            <area-radio
              v-model="form.area_id"
              :all="false"
              :other="true"
              :choose="false"
            />
          </el-form-item>

          <el-form-item label="金额" prop="amount">
            <el-input
              v-model="form.amount"
              style="width: 130px"
              @input="handleInput"
            />
          </el-form-item>

          <el-form-item label="到期还款日" prop="deadline">
            <el-date-picker
              v-model="form.deadline"
              type="date"
              style="width: 130px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="还款人" prop="grandfather">
            <el-input v-model="form.grandfather" style="width: 130px" />
          </el-form-item>
          <el-form-item label="联系方式" prop="grandfather_tel">
            <el-input v-model="form.grandfather_tel" style="width: 130px" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" style="width: 300px" />
          </el-form-item>

          <el-form-item label="相关材料" prop="images">
            <image-upload :limit="99" v-model="form.images" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="save">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </ele-card>

      <Vehicle v-model="showVehicle" @done="chooseDone" />
    </ele-page>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { updateBill } from '@/api/company';
  import Vehicle from '@/views/trade/components/choose-vehicle.vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import { useFormData } from '@/utils/use-form-data';
  import AreaRadio from '@/components/AreaRadio/index.vue';

  const emit = defineEmits(['done', 'update:modelValue']);
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    vehicleId: {
      type: Number,
      default: 0
    },
    plateNumber: String
  });

  const title = ref('');

  /** 选择车辆 */
  const showVehicle = ref(false);
  const openVehicle = () => {
    showVehicle.value = true;
  };

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: '',
    vehicle_id: 0,
    plate_number: '',
    area_id: '',
    area: '',
    company: '',
    remark: '',
    grandfather_tel: '',
    grandfather: '',
    amount: '',
    cate: '欠款',
    images: '',
    deadline: ''
  });

  const rules = reactive({
    amount: [
      {
        required: true,
        message: '请填写金额',
        type: 'string',
        trigger: 'blur'
      }
    ],
    cate: [
      {
        required: true,
        message: '请选择账单类型',
        type: 'string',
        trigger: 'blur'
      }
    ],
    deadline: [
      {
        required: true,
        message: '请选择到期还款日',
        type: 'string',
        trigger: 'blur'
      }
    ],
    grandfather_tel: [
      {
        required: true,
        message: '请填写联系电话',
        type: 'string',
        trigger: 'blur'
      }
    ],
    grandfather: [
      {
        required: true,
        message: '请填写联系人',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const handleInput = () => {
    let value = form.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    form.amount = value;
  };

  /** 提交 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      var requestData = Object.assign({}, form);

      updateBill(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          console.log(e);
        });
    });
  };

  /** 选择完车辆 */
  const selectedVehicle = ref('');
  const vehicle = ref([]);
  const chooseDone = (e) => {
    showVehicle.value = false;
    form.vehicle_id = e.id;
    form.company = e.company;
    form.plate_number = e.plate_number;
    form.area_id = e.area_id;
    form.area = e.area;
    selectedVehicle.value = e.plate_number + ' - ' + e.company;
    vehicle.value = e;
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        vehicle.value = [];
        if (props.data) {
          assignFields({
            ...props.data
          });
          console.log(props.data.area_id, 'area_id');
          selectedVehicle.value =
            props.data.plate_number + ' - ' + props.data.company;
        }
      } else {
        console.log('关闭');
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
